import React, { useEffect, useState, useDebugValue } from 'react'
import { Card, Form, Select, Input, Button, Table, Space } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { useNavigate } from 'react-router-dom'
import {
  IprovinceList,
  IhospitalList,
  IhospitalItem,
} from '@api/hospital/hospitalList/model/hospitalListTypes'
import {
  reqGetProvince,
  reqGetCityOrDistrict,
  reqGetHospitalList,
} from '@api/hospital/hospitalList'

const { Option } = Select

let flag = false // 表示是否点击了查询按钮

export default function HospitalList() {
  const navigate = useNavigate()
  // 省数据状态
  const [province, setProvince] = useState<IprovinceList>()
  // 市数据状态
  const [city, setCity] = useState<IprovinceList>()
  // 区数据状态
  const [district, setDistrict] = useState<IprovinceList>()

  // 医院类型状态
  const [hospitalTypes, setHospitalTypes] = useState<IprovinceList>()

  // 分页相关的状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(50)

  // 用来存储医院列表数据的状态
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])

  // 表格加载效果的状态
  const [loading, setLoading] = useState<boolean>(false)

  const [form] = Form.useForm()

  useEffect(() => {
    // 组件挂载获取省数据
    getProvinceList()

    // 组件挂载获取医院类型数据
    getHospitalTypes()

    // 组件挂载获取医院类表数据
    getHospitalList(page, pageSize)
  }, [])

  // 获取省数据
  async function getProvinceList() {
    const result = await reqGetProvince()
    setProvince(result)
  }
  // 获取市数据
  async function getCityList(value: string) {
    // 如果重新选择了省,就会触发这个函数去获取市的数据
    // 我们正好可以在这里,清除上一次市和区选择的数据
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined })

    const result = await reqGetCityOrDistrict(value)
    setCity(result)
  }

  // 获取区数据
  async function getDistrictList(value: string) {
    // 重新选择了市,清除上一次选择的区
    form.setFieldsValue({ districtCode: undefined })
    const result = await reqGetCityOrDistrict(value)
    setDistrict(result)
  }

  // 获取医院类型
  async function getHospitalTypes(value: string = '10000') {
    const result = await reqGetCityOrDistrict(value)
    setHospitalTypes(result)
  }

  // 获取医院列表数据的方法
  async function getHospitalList(page: number, pageSize: number) {
    let result
    setLoading(true)
    if (flag) {
      // 已经点击了查询,所以获取数据时,要添加筛选条件
      const params = form.getFieldsValue()
      result = await reqGetHospitalList({ page, limit: pageSize, ...params })
    } else {
      // 没有点击查询按钮或点击了清空,获取数据时,不添加筛选条件
      result = await reqGetHospitalList({ page, limit: pageSize })
    }

    setLoading(false)
    setTotal(result.totalElements)
    setHospitalList(result.content)
  }

  // 查询按钮的事件处理函数
  function onFinish() {
    flag = true
    setPage(1)
    getHospitalList(1, pageSize)
  }

  // 清空按钮的事件处理函数
  function clearFormHandle() {
    flag = false
    setPage(1)
    form.resetFields() // 重置表单的方法
    getHospitalList(1, pageSize)
  }

  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',
      render: (a: any, b: any, index: number) => {
        return index + 1
      },
      align: 'center',
    },
    {
      title: '医院logo',
      render: (hospital) => {
        return (
          <img
            src={`data:image/png;base64,` + hospital.logoData}
            alt=""
            width={80}
          />
        )
      },
      align: 'center',
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render: (hospital) => {
        return hospital.param.hostypeString
      },
    },
    {
      title: '详细地址',
      render: (hospital) => {
        return hospital.param.fullAddress
      },
    },
    {
      title: '状态',
      render: (hospital) => {
        return hospital.status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (hospital) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalList/show/${hospital.id}`)
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(
                  `/syt/hospital/hospitalList/hospitalSchedule/${hospital.hoscode}`
                )
              }}
            >
              排班
            </Button>
            <Button type="primary">{hospital.status ? '下线' : '上线'}</Button>
          </Space>
        )
      },
    },
  ]
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={onFinish}>
        <Form.Item name="provinceCode">
          <Select
            // value={3}
            placeholder="请选择省"
            style={{ width: 180 }}
            onChange={getCityList}
          >
            {province?.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            placeholder="请选择市"
            style={{ width: 180 }}
            onChange={getDistrictList}
          >
            {city?.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select placeholder="请选择区" style={{ width: 180 }}>
            {district?.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号"></Input>
        </Form.Item>
        <Form.Item name="hostype">
          <Select placeholder="医院类型" style={{ width: 180, marginTop: 20 }}>
            {hospitalTypes?.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            value={0}
            style={{ width: 180, marginTop: 20 }}
            placeholder="医院状态"
          >
            <Option value={1}>已上线</Option>
            <Option value={0}>未上线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            style={{ marginRight: 10, marginTop: 20 }}
            htmlType="submit"
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button
            type="default"
            style={{ marginTop: 20 }}
            onClick={clearFormHandle}
          >
            清空
          </Button>
        </Form.Item>
      </Form>

      <Table
        loading={loading}
        columns={columns}
        dataSource={hospitalList}
        style={{ marginTop: 20 }}
        rowKey="id"
        bordered
        pagination={{
          total,
          current: page,
          pageSize,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15],
          showTotal: (total) => {
            return `总共:${total}条`
          },
          onChange: (page, pageSize) => {
            setPage(page)
            setPageSize(pageSize)
            getHospitalList(page, pageSize)
          },
        }}
      ></Table>
    </Card>
  )
}
